const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

function init() {
  canvas.width = window.innerWidth * devicePixelRatio
  canvas.height = window.innerHeight * devicePixelRatio
}

init()

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

class Point {
  constructor() {
    this.r = getRandomInt(1, 5)
    this.x = getRandomInt(0, canvas.width - this.r / 2)
    this.y = getRandomInt(0, canvas.height - this.r / 2)
    this.xSpeed = getRandomInt(-2, 2)
    this.ySpeed = getRandomInt(-2, 2)
    this.lastDrawTime = null
  }

  draw() {
    if (this.lastDrawTime) {
      // 计算时间差
      const deltaTime = (Date.now() - this.lastDrawTime) / 1000
      // 计算移动距离
      const moveDistance = deltaTime * 60
      const x = this.x + this.xSpeed * moveDistance
      const y = this.y + this.ySpeed * moveDistance
      if (x < this.r / 2 || x > canvas.width - this.r / 2) {
        this.xSpeed = -this.xSpeed
      }
      if (y < this.r / 2 || y > canvas.height - this.r / 2) {
        this.ySpeed = -this.ySpeed
      }
      // 更新位置
      this.x = x
      this.y = y
    }
    ctx.beginPath()
    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(200, 200, 200, 0.5)'
    ctx.fill()
    // 更新绘制时间
    this.lastDrawTime = Date.now()
  }
}

class Graph {
  constructor(pointNumber = 30, maxDistance = 200) {
    this.points = new Array(pointNumber).fill(0).map(() => new Point())
    this.maxDistance = maxDistance
  }

  draw() {
    requestAnimationFrame(() => this.draw())
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    for (let i = 0; i < this.points.length; i++) {
      const point1 = this.points[i]
      point1.draw()
      for (let j = i + 1; j < this.points.length; j++) {
        const point2 = this.points[j]
        const distance = Math.sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2)
        if (distance > this.maxDistance) {
          continue
        }
        ctx.beginPath()
        ctx.moveTo(point1.x, point1.y)
        ctx.lineTo(point2.x, point2.y)
        ctx.closePath()
        ctx.strokeStyle = `rgba(200, 200, 200, ${1 - distance / this.maxDistance})`
        ctx.stroke()
      }
    }
  }
}

const graph = new Graph()
graph.draw()